# -*- coding: utf_8 -*-
# @Time : 2021/8/10 0010 16:44
# @Author : lyw
# @Remark : 数据源server
from mxsoftpy import Server

from mxsoftpy.exception import DBError
import model.common.IOTManager.Janitor.data_origin as data_origin
from utils.classes.custom_exception import VerifyError
from utils.public.params_method import pagination, get_pagination_params
from db.common.IOTManager.Janitor.data_origin import (DataOriginDB, ADDDataOriginDB, EchoOriginDB, GetConfigFieldDB,
                                                      GetDataOriginDB, SelectDataOriginDB)


class DataOriginServer(Server):
    __db__ = DataOriginDB

    def get_data_origin_model(self):
        """
        获取model
        @return:
        """
        return self.db.get_origin_model()


class ADDDataOrigin(Server):
    __db__ = ADDDataOriginDB

    def __init__(self, type_id):
        model = {"1": "ActiveRequestModel", "2": "DevicePushModel", "3": "ScriptPushModel", }
        self.__model__ = getattr(data_origin, model[type_id])
        self.type_id = type_id
        super().__init__()

    def add_data_origin(self, **kwargs):
        """添加数据源"""
        kwargs["type_id"] = self.type_id
        if not kwargs.get("model_id", "").isdigit():
            raise VerifyError("model_id 参数不正确")
        origin_param = self.model(**kwargs).dict()

        if self.db.query_host(host=origin_param["host"], is_del=0)[0]:
            raise VerifyError("数据源已存在...")
        origin_id = self.db.query_host(host=origin_param["host"], is_del=1)[0]
        if origin_id:
            return self.db.update(sub_key=origin_id, **origin_param)
        else:
            return self.db.create(**origin_param)

    def update_data_origin(self, **kwargs):
        """
        修改数据源
        @param kwargs:
        @return:
        """
        kwargs["type_id"] = self.type_id
        origin_param = self.model(**kwargs).dict()
        origin_param.pop("model_id")
        if not kwargs.get("origin_id"):
            raise VerifyError("origin_id不存在...")
        origin_id = ".".join(["data_origin", kwargs["origin_id"]])
        return self.db.update(sub_key=origin_id, **origin_param)


class GetDataOriginServer(Server):
    __db__ = GetDataOriginDB

    def get_origin_data(self, *, search, state, pageindex, pagesize, **kwargs):
        """
        *为占位符 表示必须有后面几个键名固定的键值对, 如果没有就报错
        :param search: 搜索内容 -->str
        :param state: 状态    -->int
        :param pageindex: 页码    -->int
        :param pagesize: 每页显示数量 -->int
        :param kwargs: 无意义参数 -->dict
        :return: 数据列表
        """
        """query_condition：查询条件"""
        query_condition = {'search': search, 'state': state, 'pageindex': pageindex, 'pagesize': pagesize}

        """ 对页码，页码显示数量校验 """
        paging = get_pagination_params(query_condition)
        """数据库操作"""
        data_all = self.db.get_origin_data(paging, **query_condition)

        """ 给返回数据添加分页 """
        """res_dict:为分页编写的数据格式"""
        res_dict = {"data": data_all[1], "total": data_all[0]}
        origin_data_list = pagination(res_dict, paging, data_all[0])

        """origin_data_list: 返回前端数据"""
        return origin_data_list


class SelectDataOriginServer(Server):
    __db__ = SelectDataOriginDB

    def update_state(self, *, origin_id, state, **kwargs):
        """
        修改是否启用
        *为占位符 表示必须有后面几个键名固定的键值对, 如果没有就报错
        :param origin_id: 数据源ID -->int
        :param state: 状态 -->int/str(数字类型)
        :param kwargs: 无意义参数 -->dict
        :return: 结果列表，具体请看API文档
        """
        """select_parameter:修改参数"""
        select_parameter = {'origin_id': origin_id, 'state': state}

        """对数据进行校验"""
        """state_operation:状态选项"""
        state_operation = {'0': 'state', '1': 'state', '2': 'is_del'}
        select_parameter['key'] = state_operation[select_parameter['state']]
        select_parameter['state'] = int(select_parameter['state'])
        if select_parameter['key'] == state_operation['2']:
            select_parameter['state'] = 1

        """操作数据库修改"""
        """ret_list:返回数据列表"""
        ret_list = []
        for origin in select_parameter["origin_id"].split(","):
            if origin:
                ret = self.db.update_state(".".join(["data_origin", origin]), select_parameter['key'],
                                           select_parameter['state'])
                ret_list.append(ret)

        return ret_list


class EchoOrigin(Server):
    __db__ = EchoOriginDB

    def echo_origin(self, **kwargs):
        """
        回显server
        @param kwargs: origin_id 数据源id
        @return:
        """

        if not kwargs.get("origin_id"):
            raise VerifyError("origin_id参数不存在...")
        origin_id = ".".join(["data_origin", kwargs["origin_id"]])
        try:
            origin, res_dict = self.db.query_host(data_origin=origin_id)
            field_list = self.db.get_field(res_dict["type_id"])
            for i in field_list:
                i["value"] = res_dict[i["name"]]
        except DBError:
            raise VerifyError("数据不存在...")

        res_dict = {"data": field_list, "door": self.db.query_door(is_del=0, origin_id=origin_id)}
        return res_dict


class GetConfigFieldServer(Server):
    __db__ = GetConfigFieldDB

    def get_field(self, **kwargs):
        """
        获取字段
        @param kwargs: type_id 获取type 的字段
        @return:
        """
        if kwargs.get("type_id") not in ("1", "2", "3"):
            raise VerifyError("type_id参数不存在...")
        return self.db.get_field(kwargs["type_id"])
